package org.common.utils;

import java.util.Random;

import org.common.constants.UserConstants;
import org.common.redis.RedisClient;
import org.common.vo.UserVo;

public class TokenUtils {
	/**
	 * 生成token
	 * 
	 * @author Mr.古
	 * @param userVo
	 * @return
	 */
	public static String buildToken(final UserVo userVo) {
		final long longTime = System.currentTimeMillis() + new Random().nextInt();
		final StringBuilder stringBuilder = new StringBuilder();
		stringBuilder.append(longTime).append(";").append(userVo.getUserId()).append(";").append(userVo.getUserName())
				.append(";").append(userVo.getUserPassWord()).append(";").append(userVo.getLoginTime());
		String token = RSAUtil.encryptData(stringBuilder.toString(), true);
		RedisClient redisClient = new RedisClient();
		redisClient.keySet(UserConstants.USER_REDIS + userVo.getUserName(), token);
		return token;
	}

	/**
	 * 验证token
	 * 
	 * @author Mr.古
	 * 
	 * @param userName
	 * @return
	 */
	public static UserVo analysisUserName(final String userName) {
		UserVo userVo = null;
		RedisClient redisClient = null;
		if (!CommonUtils.isEmpty(userName)) {
			redisClient = new RedisClient();
			String token = redisClient.keyGetKey(UserConstants.USER_REDIS + userName);
			if (!CommonUtils.isEmpty(token)) {
				analysisToken(token);
			}
		}
		return userVo;
	}

	/**
	 * 验证token
	 * 
	 * @author Mr.古
	 * @param data
	 * @return
	 */
	public static UserVo analysisToken(final String data) {
		final String tokenString = RSAUtil.encryptData(data, false);
		System.out.println(tokenString);
		final String[] strings = tokenString.split(";");
		final String loginTime = strings[4];
		UserVo userVo = null;
		if (DateUtils.isTimeRange(loginTime)) {
			userVo = new UserVo();
			userVo.setUserId(strings[1]);
			userVo.setUserName(strings[2]);
			userVo.setUserPassWord(strings[3]);
			userVo.setLoginTime(DateUtils.getLongNowTime());
		}
		return userVo;
	}

	public static void main(final String[] args) {
		final String string = "JDxfwT2+iaPOHLB+1TOHH2uc5z5Bddxbl/qBsfqOEJUf7jL41UwYbavggJJl0KDwGuw6ZNbKo9ZTlwWzyiXNGUgVU3iDw46rcdrdqfOe/1kDAYavi2TwHmttDflzHFn35DdKds/PIxuJ+Rn8DTLlgz5kygs4r3uBiPIW+rW0nHA=";
		System.out.println(string);
		System.out.println(analysisToken(string));
		// UserVo userVo = new UserVo();
		// userVo.setUserId(UUIDUtils.getUUID());
		// userVo.setUserName("小明");
		// userVo.setUserPassWord(MD5Utils.buildMD5("123"));
		// userVo.setLoginTime(DateUtils.getLongNowTime());
		// System.out.println(buildToken(userVo));
	}
}
